//
//  JHMyNewWordsListController.m
//  JuniRengLish_iOS
//
//  Created by Maiyou on 2019/6/5.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHMyNewWordsListController.h"
#import "JHMyNewWordsListCell.h"

@interface JHMyNewWordsListController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray * dataArray;

@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) FSAudioStream * audioStream;

@property (nonatomic, assign) NSInteger selectedIndex;
/** 是否正在播放 */
@property (nonatomic, assign) BOOL isPlay;
/** 播放按钮 */
@property (nonatomic, strong) UIButton * playButton;

@property (nonatomic, strong) UILabel * placeHolderLabel;

@end

@implementation JHMyNewWordsListController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"我的生词本";
    self.selectedIndex = 0;
    
    [self creatNavBtn];
    
    [self getAllWords];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.audioStream pause];
    self.audioStream = nil;
}

- (void)creatNavBtn
{
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    button.layer.cornerRadius = 15;
    button.layer.masksToBounds = YES;
    button.backgroundColor = JKGetColor(@"ca4143");
    [button setImage:[UIImage imageNamed:@"播放1"] forState:0];
    [button setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(playCurrentWords:) forControlEvents:UIControlEventTouchUpInside];
    self.playButton = button;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

#pragma mark — 播放当前的所有单词
- (void)playCurrentWords:(UIButton *)sender
{
    if (self.dataArray.count == 0) return;
    
    sender.selected = !sender.selected;
    if (!self.isPlay)
    {
        [self playAction];
        self.isPlay = YES;
    }
    else
    {
        [self.audioStream pause];
    }
}

#pragma mark — 获取数据库所有的生词
- (void)getAllWords
{
    JHKeyValueStorage * storage = [[JHKeyValueStorage alloc] init];
    self.dataArray = [storage getAllValuesFromTable:@"NewWords"];
    [self.tableView reloadData];
    
    if (self.dataArray.count > 0)
    {
        self.tableView.hidden = NO;
        self.placeHolderLabel.hidden = YES;
    }
    else
    {
        self.tableView.hidden = YES;
        self.placeHolderLabel.hidden = NO;
    }
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, JKScreenW, JKScreenH - kStatusBarAndNavigationBarHeight - kTabbarSafeBottomMargin) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 44;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(30, (JKScreenH - kStatusBarAndNavigationBarHeight - kTabbarSafeBottomMargin - 120) / 2, JKScreenW - 60, 120)];
        label.text = @"您还没有添加生词哦~\n【长按单词可以添加生词】";
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor darkGrayColor];
        label.hidden = YES;
        [self.view addSubview:label];
        self.placeHolderLabel = label;
    }
    return _tableView;
}

#pragma mark TableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseID = @"cellId";
    JHMyNewWordsListCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    if(!cell)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:@"JHMyNewWordsListCell" owner:self options:nil].firstObject;
    }
    cell.deleteBtn.tag = indexPath.row;
    cell.dataDic = self.dataArray[indexPath.row];
    cell.DeleteWord = ^{
        [self getAllWords];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"==%ld", (long)indexPath.row);
    
    JHMyNewWordsListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]];
    cell.showEnTitle.textColor = [UIColor darkTextColor];
    self.selectedIndex = indexPath.row;
    self.playButton.selected = YES;
    self.isPlay = YES;
    [self playAction];
}

- (FSAudioStream *)audioStream
{
    if (!_audioStream)
    {
        WEAKSELF
        //创建FSAudioStream对象
        _audioStream = [[FSAudioStream alloc]init];
        _audioStream.onFailure = ^(FSAudioStreamError error,NSString *description){
            NSLog(@"播放过程中发生错误，错误信息：%@",description);
        };
        _audioStream.onCompletion = ^(){
            NSLog(@"播放完成!");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf playComplete];
            });
        };
        _audioStream.onStateChange = ^(FSAudioStreamState state) {
            
        };
        [_audioStream setVolume:1];//设置声音
    }
    return _audioStream;
}
#pragma mark — 播放完成
- (void)playComplete
{
    JHMyNewWordsListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]];
    cell.showEnTitle.textColor = [UIColor darkTextColor];
    
    self.selectedIndex ++;
    if (self.selectedIndex >= self.dataArray.count)
    {
        self.selectedIndex = 0;
    }
    [self playAction];
}
//执行播放
- (void)playAction
{
    JHMyNewWordsListCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]];
    cell.showEnTitle.textColor = [UIColor blueColor];
    [self playWord:cell.showEnTitle.text];
}

- (void)playWord:(NSString *)word
{
    word = [word stringByAddingPercentEncodingWithAllowedCharacters:  [NSCharacterSet URLUserAllowedCharacterSet]];
    NSString * urlStr = [NSString stringWithFormat:@"https://fanyi.baidu.com/gettts?lan=uk&text=%@&spd=2&source=web", word];
    self.audioStream.url = [NSURL URLWithString:urlStr];
    [self.audioStream play];
}


@end
